package com.hiof.moraa.server.service;

import com.hiof.moraa.mapping.TblAthlete;
import com.hiof.moraa.mapping.TblSupport;
import com.hiof.moraa.server.dao.AthleteDAO;
import com.hiof.moraa.server.dao.AthleteLiveMediaDAO;
import com.hiof.moraa.server.dao.SupportDAO;
import com.hiof.moraa.server.dao.SupportLiveMediaDAO;
import com.hiof.moraa.server.service.model.LiveMediaFeed;
import com.hiof.moraa.server.service.model.SupportLiveMediaFeed;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.processing.SupportedSourceVersion;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Bergy
 */
@Transactional(propagation = Propagation.REQUIRED)
public class MediaService {
    private AthleteLiveMediaDAO athleteLiveMediaDAO;
    private SupportLiveMediaDAO supportLiveMediaDAO;
    private AthleteDAO athleteDAO;

    public void setAthleteLiveMediaDAO(AthleteLiveMediaDAO athleteLiveMediaDAO) {
        this.athleteLiveMediaDAO = athleteLiveMediaDAO;
    }

    public void setSupportLiveMediaDAO(SupportLiveMediaDAO supportLiveMediaDAO) {
        this.supportLiveMediaDAO = supportLiveMediaDAO;
    }

    public void setAthleteDAO(AthleteDAO athleteDAO) {
        this.athleteDAO = athleteDAO;
    }

    public List<LiveMediaFeed> getAllMediaOfAthlete(int athleteId) {
        TblAthlete athlete = athleteDAO.getAthleteById(athleteId);
        return getAllMediaOfAthlete(athlete);
    }

    public List<LiveMediaFeed> getAllMediaOfOneAthleteByUserIdAndRouteId(int userId, int routeId) {
        TblAthlete athlete = athleteDAO.getAthleteByUserIdAndRouteId(userId, routeId);
        return getAllMediaOfAthlete(athlete);
    }

    public List<LiveMediaFeed> getAllMediaOfOneAthleteByUsernameAndRouteId(String username, int routeId) {
        TblAthlete athlete = athleteDAO.getAthleteByUsernameAndRouteId(username, routeId);
        return getAllMediaOfAthlete(athlete);
    }

    private List<LiveMediaFeed> getAllMediaOfAthlete(TblAthlete athlete) {
        List<LiveMediaFeed> result = new ArrayList<LiveMediaFeed>();
        if (athlete != null) {
            result.addAll(athleteLiveMediaDAO.getAllMediaFeedByAthleteId(athlete.getId()));
            List<TblSupport> supports = athleteDAO.getSupports(athlete.getId());
            for(TblSupport support : supports){
                result.addAll(getAllMediaOfSupport(support.getId()));
            }
        }
        return result;
    }

    private List<LiveMediaFeed> getAllMediaOfSupport(int supportId) {
        List<LiveMediaFeed> result = new ArrayList<LiveMediaFeed>();
        for (SupportLiveMediaFeed feed : supportLiveMediaDAO.getAllMediaFeedBySupportId(supportId)) {
            result.add(feed);
        }
        return result;
    }
}
